package Principal;

import de.centigrade.bizlaf.BizLafControl;
import de.centigrade.bizlaf.support.BizLafStyles;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import preparedstatement.DebugLevel;
import preparedstatement.StatementFactory;

/**
 *
 * @author pato
 */
public final class ventas extends javax.swing.JFrame {

    PreparedStatement ps;
    ResultSet rs;
    DefaultTableModel dtm;
    ResultSetMetaData rsm;
    int idUsuario;
    int idCliente = 0;
    static Thread imprimiendo;
    int folio = 0;
    float debe = 0.0f;

    /**
     * Creates new form ventas
     */
    public ventas() {
        initComponents();
        if (VentanaPrincipal.giro.equals("Celulares")) {
            especiales.setVisible(true);
            jTable2.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    int r = jTable2.rowAtPoint(e.getPoint());
                    int c = jTable2.columnAtPoint(e.getPoint());
                    if (r >= 0 && r < jTable2.getRowCount()) {
                        jTable2.setRowSelectionInterval(r, r);
                        if (c >= 0) {
                            jTable2.setColumnSelectionInterval(c, c);
                        }
                    } else {
                        jTable2.clearSelection();
                    }

                    int rowindex = jTable2.getSelectedRow();
                    if (rowindex < 0) {
                        return;
                    }
                    if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
                        JPopupMenu popup = jPopupMenu1;
                        popup.show(e.getComponent(), e.getX(), e.getY());
                    }
                }
            });
        } else {
            especiales.setVisible(false);
        }
        BizLafControl.get().setStyle(jPanel4, BizLafStyles.CONTAINER);
        BizLafControl.get().setStyle(jPanel1, BizLafStyles.CONTAINER);
        BizLafControl.get().setStyle(jPanel2, BizLafStyles.CONTAINER);
        BizLafControl.get().setStyle(jPanel3, BizLafStyles.CONTAINER);
        BizLafControl.get().setStyle(jTextField1, BizLafStyles.SEARCH);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(50);
        jTable1.getColumnModel().getColumn(1).setMaxWidth(50);
        jTextField1.setDocument(new LimitadorCaracteres());
        jTextField1.requestFocus();
        jTable2.getColumnModel().getColumn(0).setMaxWidth(40);
        jTable2.getColumnModel().getColumn(1).setMaxWidth(40);
        jTable2.getColumnModel().getColumn(2).setPreferredWidth(80);
        jTable2.getColumnModel().getColumn(4).setMaxWidth(50);
        jTable2.getColumnModel().getColumn(5).setMaxWidth(50);
        jTable2.getColumnModel().getColumn(6).setMaxWidth(50);
        jTable2.getColumnModel().getColumn(3).setMaxWidth(100);
        // Detalle.setEnabled(false);
        cargarDatos();
    }

    void cargarDatos() {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
        dtm = (DefaultTableModel) this.jTable1.getModel();
        dtm.setRowCount(0);
        String select;
        String  fecha;
        try {
            if (jDateChooser1.getDate() == null) {
                fecha = "current_date";
            } else {
                fecha = "'" + sdf.format(jDateChooser1.getDate()) + "'";
            }

            select = "select  folio, ticket, detalle,fecha from venta where sucursal = ? " + (canceladas.isSelected() ? "" : "and activo =1") + ((jTextField1.getText().equals(""))?(" and date(fecha) = " + fecha ):(" and folio like '%" + jTextField1.getText()+"%'")) + " order by fecha desc";
            ps = local_connection.cn.prepareStatement(select);
            ps.setInt(1, VentanaPrincipal.sucursal);
                        System.out.println(select);

            rs = ps.executeQuery();
//            rsm = (com.mysql.jdbc.ResultSetMetaData) (ResultSetMetaData) rs.getMetaData();
            ArrayList<Object[]> data = new ArrayList<>();

            while (rs.next()) {
                Object[] rows = new Object[jTable1.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                data.add(rows);
            }

            for (int i = 0; i < data.size(); i++) {
                dtm.addRow(data.get(i));
            }

        } catch (SQLException e) {
            VentanaPrincipal.logger.log(Level.INFO, null, e);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        especiales = new javax.swing.JMenuItem();
        dns = new javax.swing.JMenuItem();
        jPanel4 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();
        Detalle = new javax.swing.JButton();
        CancelarVenta = new javax.swing.JButton();
        imprimeTicket = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        canceladas = new javax.swing.JCheckBox();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        vendedort = new javax.swing.JLabel();
        clientet = new javax.swing.JLabel();
        pesot = new javax.swing.JLabel();
        netot = new javax.swing.JLabel();
        descuentot = new javax.swing.JLabel();
        totalt = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        tipopagot = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        resta = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();
        editarLinea = new javax.swing.JButton();
        Devolucion = new javax.swing.JButton();

        especiales.setText("Ver Vendidos");
        especiales.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                especialesActionPerformed(evt);
            }
        });
        jPopupMenu1.add(especiales);

        dns.setText("Ver DN/Folio");
        dns.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dnsActionPerformed(evt);
            }
        });
        jPopupMenu1.add(dns);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconImage(new ImageIcon(getClass().getResource("/Imagenes/logo_rayito.png")).getImage());

        jTextField1.setText(" ");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jDateChooser1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jDateChooser1PropertyChange(evt);
            }
        });
        jDateChooser1.addVetoableChangeListener(new java.beans.VetoableChangeListener() {
            public void vetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {
                jDateChooser1VetoableChange(evt);
            }
        });

        Detalle.setText("Detalle");
        Detalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DetalleActionPerformed(evt);
            }
        });

        CancelarVenta.setText("Cancelar V");
        CancelarVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelarVentaActionPerformed(evt);
            }
        });

        imprimeTicket.setText("Imprimir Ticket");
        imprimeTicket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                imprimeTicketActionPerformed(evt);
            }
        });

        jButton1.setText("Abonar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        canceladas.setText("Ventas Canceladas");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(canceladas)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(Detalle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jDateChooser1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(CancelarVenta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(imprimeTicket, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(canceladas)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Detalle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(imprimeTicket)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CancelarVenta))
        );

        jLabel2.setText("Vendedor:");

        jLabel4.setText("Cliente:");

        jLabel5.setText("Peso Total (GR):");

        jLabel6.setText("Total Neto $:");

        jLabel7.setText("Descuento $:");

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel8.setText("$");

        vendedort.setText("---");

        clientet.setText("---");

        pesot.setText("----");

        netot.setText("---");

        descuentot.setText("---");

        totalt.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        totalt.setText("---");

        jLabel1.setText("Tipo de pago:");

        tipopagot.setText("------");

        jLabel3.setText("Restan $:");

        resta.setText("---");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tipopagot))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(resta)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(clientet, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pesot))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel8)
                                        .addComponent(jLabel7)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(netot)
                                    .addComponent(totalt)
                                    .addComponent(descuentot, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(vendedort, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tipopagot))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(vendedort))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(clientet)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(resta))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(pesot))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(netot))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(descuentot))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(totalt))
                .addContainerGap())
        );

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Cantidad", "Nombre", "Descuento", "P-Unit", "Importe", "Peso", "Tipo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Float.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jButton4.setText("Buscar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Folio", "Numero", "Detalles", "Fecha"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTable1KeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton3.setText("Salir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        editarLinea.setText("Editar Linea");
        editarLinea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editarLineaActionPerformed(evt);
            }
        });

        Devolucion.setText("Devolucion");
        Devolucion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DevolucionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(editarLinea, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE)
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(Devolucion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(Devolucion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(editarLinea, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addComponent(jTextField1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton4))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 598, Short.MAX_VALUE))
                .addContainerGap())
        );

        jPanel4Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jPanel2, jPanel3});

        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    class LimitadorCaracteres extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        @Override
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!Character.isDigit(arg1.charAt(i))) {
                    return;
                }
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
    private void imprimeTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imprimeTicketActionPerformed
        imprimir();
        // TODO add your handling code here:
    }//GEN-LAST:event_imprimeTicketActionPerformed
    private void imprimir() {

        if (jTable1.getSelectedRow() != -1) {
            float credito = 0.0f;
            Ticket.subCabezaLineas.clear();
            Ticket.importes.clear();
            Ticket.nombres.clear();
            Ticket.nombre = "";
            Ticket.items.clear();
            Ticket.tipopago = tipopagot.getText();
            Ticket.impreso = false;
            if (idCliente != 0) {
                Ticket.nombre = clientet.getText();
            }
            if (debe > 0) {
                try {
                    ps = local_connection.cn.prepareStatement("select (credito-restante) from credito where folio = ?");
                    ps.setInt(1, folio);
                    rs = ps.executeQuery();
                    rs.next();
                    System.out.println("si debe");
                    Ticket.credito = true;
                    credito = rs.getFloat(1);
                    Ticket.saldo = credito;
                } catch (SQLException ex) {
                    Logger.getLogger(ventas.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            /*  Ticket.subCabezaLineas.clear();
             Ticket.importes.clear();
             Ticket.nombres.clear();
             Ticket.items.clear();
             Ticket.impreso = false;*/
            Date date = (Date) jTable1.getValueAt(jTable1.getSelectedRow(), 3);
            SimpleDateFormat fecha = new SimpleDateFormat("dd/MM/yyyy");
            SimpleDateFormat hora = new SimpleDateFormat("hh:mm:ss aa");

            /*Ticket.AddCabecera("REPECO");
             Ticket.AddCabecera("Michel Morales Molina");
             Ticket.AddCabecera("RFC MOMM8804289V1");
             Ticket.AddCabecera("11 PONIENTE 113 COLONIA CENTRO");
             Ticket.AddCabecera("PUEBLA, PUE. TEL.(222)232-1705");
             Ticket.AddCabecera(Ticket.DarEspacio());*/
            Ticket.AddSubCabecera("" + fecha.format(date) + " " + hora.format(date));
            Ticket.AddSubCabecera("Ticket # " + String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 1)));
            Ticket.AddSubCabecera("Folio: " + String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 0)));
            for (int i = 0; i < jTable2.getRowCount(); i++) {
                Ticket.AddNombre(String.valueOf(jTable2.getValueAt(i, 2)));
                Ticket.AddImporte(String.valueOf(jTable2.getValueAt(i, 5)) + '0');
                Ticket.AddItem(String.valueOf(jTable2.getValueAt(i, 1)), String.valueOf(jTable2.getValueAt(i, 0)), String.valueOf(jTable2.getValueAt(i, 4)));
            }
            Ticket.setTotal(totalt.getText());
            Ticket.setPeso(pesot.getText());
            Ticket.setRecibido(String.valueOf(Float.parseFloat(totalt.getText()) - credito));
            /*Ticket.AddPieLinea("¡GRACIAS POR TU COMPRA!");
             Ticket.AddPieLinea("www.teslabem.com");*/
            if (imprimiendo != null) {
                if (!imprimiendo.isAlive()) {
                    imprimiendo = new Thread(new imprimir());
                    imprimiendo.start();
                }

            } else {
                imprimiendo = new Thread(new imprimir());
                imprimiendo.start();
            }
            jTextField1.requestFocus();
        }
    }
    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
//        consultarVentas();
// TODO add your handling code here:
    }//GEN-LAST:event_jTextField1KeyReleased

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        seleccion();
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked
    void seleccion() {
        int row = jTable1.getSelectedRow();
        if (row != -1) {
            String cliente = "", usuario = "", tipo = "";
            float total = 0, neto = 0, descuento = 0;
            int peso = 0;
            dtm = (DefaultTableModel) this.jTable2.getModel();
            dtm.setRowCount(0);
            ArrayList<Object[]> data = new ArrayList<>();
            Object[] rows = new Object[jTable2.getColumnCount()];
            try {
                folio = (int) (jTable1.getValueAt(row, 0));
                ps = local_connection.cn.prepareStatement("select productos.id_producto,cantidad,if(detalleventa.id_producto=-2,(select nombre from otros where detalle_venta = idetalle),productos.nombre) as nombre,\n"
                        + "modo,preciovendido,(preciovendido*cantidad) as importe,(productos.peso*cantidad) as peso,productos.tipo,\n"
                        + "concat(c.nombre,' ',c.paterno,' ',c.materno) as cliente,\n"
                        + "concat(u.nombre,' ',u.paterno,' ',u.materno) as usuario, ticket, tipopago,id_cliente, (credito-restante) as debe \n"
                        + "from venta join detalleventa on detalleventa.folio= venta.folio \n"
                        + "left join credito on venta.folio = credito.folio \n"
                        + "join productos on productos.id_producto = detalleventa.id_producto join personas c on venta.id_cliente= c.id_persona \n"
                        + "join personas u on venta.id_usuario = u.id_persona where detalleventa.folio = ?");
                ps.setInt(1, folio);
                rs = ps.executeQuery();
                while (rs.next()) {
                    rows[0] = rs.getString("id_producto");
                    rows[1] = rs.getFloat("cantidad");
                    rows[2] = rs.getString("nombre");
                    rows[3] = rs.getString("modo");
                    rows[4] = rs.getFloat("preciovendido");
                    rows[5] = rs.getFloat("importe");
                    rows[6] = rs.getInt("peso");
                    rows[7] = rs.getString("tipo");
                    data.add(rows);
                    peso += (int) rows[6];
                    if ((float) rows[5] > 0) {
                        neto += (float) rows[5];
                    } else {
                        descuento += (float) rows[5];
                    }
                    dtm.addRow(data.get(0));
                    cliente = rs.getString("cliente");
                    usuario = rs.getString("usuario");
                    tipo = rs.getString("tipopago");
                    idCliente = rs.getInt("id_cliente");
                    debe = (rs.getObject("debe") == null) ? 0.0f : rs.getFloat("debe");
                }

                data.clear();
                total = neto + descuento;
                resta.setText(String.valueOf(debe));
                tipopagot.setText(tipo);
                clientet.setText(cliente);
                vendedort.setText(usuario);
                netot.setText(String.valueOf(neto));
                totalt.setText(String.valueOf(total));
                pesot.setText(String.valueOf(peso));
                descuentot.setText(String.valueOf(descuento));
            } catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.INFO, null, ex);
            }
            //cargar datos al jTable2
        }
    }
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        cargarDatos();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyReleased
        seleccion();        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1KeyReleased

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void DetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DetalleActionPerformed

        int row = jTable1.getSelectedRow();
        if (row != -1) {
            ModificarDetalleVenta modDetalle = new ModificarDetalleVenta((Integer) jTable1.getValueAt(row, 0));
            modDetalle.setVisible(true);
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_DetalleActionPerformed

    private void jDateChooser1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jDateChooser1PropertyChange

        if (ps != null) {
            cargarDatos();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jDateChooser1PropertyChange

    private void jDateChooser1VetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {//GEN-FIRST:event_jDateChooser1VetoableChange
        // TODO add your handling code here:
    }//GEN-LAST:event_jDateChooser1VetoableChange

    private void CancelarVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelarVentaActionPerformed
        int row = jTable1.getSelectedRow();
        if (row != -1) {
            cancelarV();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_CancelarVentaActionPerformed

    private void editarLineaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarLineaActionPerformed
        int borrar, row1, codigo, row = jTable2.getSelectedRow();
        if (row != -1) {
            try {
                CancelarCantidad cantidad = new CancelarCantidad(this, true, (int) (float) jTable2.getValueAt(row, 1));
                row1 = jTable1.getSelectedRow();
                codigo = (int) (jTable1.getValueAt(row1, 0));
                borrar = cantidad.showDialog();
                if (borrar == 0) {
                    ps = StatementFactory.getStatement(local_connection.cn, "delete from detalleventa where folio = ? and id_producto = ? and preciovendido = ?", DebugLevel.ON);
                } else {
                    ps = StatementFactory.getStatement(local_connection.cn, "update detalleventa set cantidad = " + borrar + " where folio = ? and id_producto = ? and preciovendido = ?", DebugLevel.ON);
                }
                ps.setInt(1, codigo);
                ps.setInt(2, Integer.valueOf(String.valueOf(jTable2.getValueAt(row, 0))));
                ps.setFloat(3, Float.valueOf(String.valueOf(jTable2.getValueAt(row, 4))));
                ps.execute();
                VentanaPrincipal.guardarCache(ps, "detalleventa", true);
            } // TODO add your handling code here:
            catch (SQLException e) {
                VentanaPrincipal.logger.log(Level.INFO, null, e);

            }
            seleccion();
            imprimir();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_editarLineaActionPerformed

    private void DevolucionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DevolucionActionPerformed
        int codigo, venta;
        float can;
        String nombre;
        int sucu = 0;
        int row = jTable2.getSelectedRow();
        if (row != -1) {
            row = jTable2.convertRowIndexToModel(row);
            codigo = Integer.parseInt((String) jTable2.getValueAt(row, 0));
            can = Float.parseFloat(String.valueOf(jTable2.getValueAt(row, 1)));
            venta = Integer.parseInt(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());
            nombre = jTable2.getValueAt(jTable2.getSelectedRow(), 2).toString();

            try {
                ps = (PreparedStatement) local_connection.cn.prepareStatement("select sucursal from venta where folio =" + venta);
                rs = ps.executeQuery();
                rs.next();
                sucu = rs.getInt(1);
            } catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.INFO, null, ex);
            }

            new devolucion(codigo, can, venta, sucu, nombre).setVisible(true);

        }
        // TODO add your handling code here:
    }//GEN-LAST:event_DevolucionActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (jTable1.getSelectedRow() != -1) {
            (new credito(idCliente, clientet.getText())).setVisible(true);
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void especialesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_especialesActionPerformed
        int row1 = jTable1.getSelectedRow();
        if (row1 != -1) {
            folio = (int) (jTable1.getValueAt(row1, 0));
            int row2 = jTable2.getSelectedRow();
            if (row2 !=-1) {
                int id = Integer.parseInt((String) jTable2.getValueAt(row2, 0));
                String nombre = String.valueOf(jTable2.getValueAt(row2, 2));
                String tipo = String.valueOf(jTable2.getValueAt(row2, 7));
                if(tipo.equals("Celular")||tipo.equals("Chip"))
                (new verEspecialesVendidos(this, true,folio,id,nombre,tipo)).setVisible(true); 
            }
        }
    }//GEN-LAST:event_especialesActionPerformed

    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
        if(jTable2.getSelectedRow()!=-1)
            if(String.valueOf(jTable2.getValueAt(jTable1.getSelectedRow(), 7)).equals("Chip"));
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable2MouseClicked

    private void dnsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dnsActionPerformed
             int row1 = jTable1.getSelectedRow();
        if (row1 != -1) {
            folio = (int) (jTable1.getValueAt(row1, 0));
            int row2 = jTable2.getSelectedRow();
            if (row2 !=-1) {
                int id = Integer.parseInt((String) jTable2.getValueAt(row2, 0));
                String nombre = String.valueOf(jTable2.getValueAt(row2, 2));
                String tipo = String.valueOf(jTable2.getValueAt(row2, 7));
                if(tipo.equals("Celular")||tipo.equals("Chip"))
                (new VerDN(this, true,folio,id,nombre,tipo)).setVisible(true); 
                else
                    JOptionPane.showMessageDialog(null, "Esta opcion solo esta disponible para Chips");
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_dnsActionPerformed

    private void cancelarV() {
        int codigo;
        int row = jTable1.getSelectedRow();
        codigo = (int) (jTable1.getValueAt(row, 0));
        try {
            // ps = (PreparedStatement) cn.prepareStatement("DELETE a.*, b.* FROM venta as a, detalleventa as b WHERE a.folio = b.folio AND a.folio = ?");
            //  ps = StatementFactory.getStatement(local_connection.cn, "DELETE FROM venta WHERE folio = ? and sucursal = ?", DebugLevel.ON);
            ps = StatementFactory.getStatement(local_connection.cn, "UPDATE venta SET activo = 0 WHERE folio = ? and sucursal = ?", DebugLevel.ON);
            ps.setInt(1, codigo);
            ps.setInt(2, VentanaPrincipal.sucursal);
            ps.execute();
            VentanaPrincipal.guardarCache(ps, "venta", true);
            // TODO add your handling code here:
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.INFO, null, ex);
        }
        cargarDatos();
        DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
        model.setRowCount(0);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelarVenta;
    private javax.swing.JButton Detalle;
    private javax.swing.JButton Devolucion;
    private javax.swing.JCheckBox canceladas;
    private javax.swing.JLabel clientet;
    private javax.swing.JLabel descuentot;
    private javax.swing.JMenuItem dns;
    private javax.swing.JButton editarLinea;
    private javax.swing.JMenuItem especiales;
    private javax.swing.JButton imprimeTicket;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JLabel netot;
    private javax.swing.JLabel pesot;
    private javax.swing.JLabel resta;
    private javax.swing.JLabel tipopagot;
    private javax.swing.JLabel totalt;
    private javax.swing.JLabel vendedort;
    // End of variables declaration//GEN-END:variables
}
